package com.message.queue.rabbit.base;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @包名称 com.message.queue.rabbit.base
 * @类描述 <pre></pre>
 * @作者 zhangbo
 * @创建时间 2020/7/16.
 * @版本 1.00
 * @修改记录 <pre>
 *     版本           修改人         修改日期         修改内容描述
 *     -----------------------------------------------------------
 *     1.00           zhangbo        2020/7/16.           类创建
 *     -----------------------------------------------------------
 * </pre>
 */
public class Consumer {

    public static void main(String[] args) throws IOException, TimeoutException {

        /*1、创建一个连接工厂*/
        ConnectionFactory connectionFactory = new ConnectionFactory();
        /*配置参数属性*/
        connectionFactory.setHost("172.16.24.182");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        /*2、创建一个连接*/
        Connection connection = connectionFactory.newConnection();

        /*3、创建一个channel*/
        Channel channel = connection.createChannel();


        String queueName = "testQueue";

        AMQP.Queue.DeclareOk declareOk = channel.queueDeclarePassive(queueName);

        System.out.println("队列准备就绪的消息数：" + declareOk.getMessageCount());

        boolean autoAck = false;

        channel.basicConsume(queueName, autoAck, "myConsumerTag", new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String routingKey = envelope.getRoutingKey();
                System.out.println("routingKey:" + routingKey + ",body:" + new String(body));
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        });


        /*关闭连接*/
//        channel.close();
//        connection.close();

    }
}
